﻿/*
 * @author: wizardc
 */

using System;
using System.Collections.Generic;
using System.IO;
using Dou.Resource;
using DouEditor.Const;
using DouEditor.Resource.ABBuild;
using DouEditor.Utils;
using UnityEngine;

namespace DouEditor.Resource.HotFixed
{
    /// <summary>
    /// 收集打包资源的所有数据清单文件
    /// </summary>
    public class CollectResourceManifest
    {
        public void Collect(BuildRule buildRule, ABInfo abInfo)
        {
            var manifestPath = Path.Combine(buildRule.realOutputPath, BuildConst.BuildFolderName);
            
            var assetBundle = AssetBundle.LoadFromFile(manifestPath);
            var assetBundleManifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

            var resourceManifest = new ResourceManifest();

            resourceManifest.abName = abInfo.abEncryptName;
            resourceManifest.allABFile = assetBundleManifest.GetAllAssetBundles();
            resourceManifest.directDependents = new Dictionary<string, string[]>();
            resourceManifest.dependents = new Dictionary<string, string[]>();
            foreach (var abName in resourceManifest.allABFile)
            {
                resourceManifest.directDependents.Add(abName, assetBundleManifest.GetDirectDependencies(abName));
                resourceManifest.dependents.Add(abName, assetBundleManifest.GetAllDependencies(abName));
            }
            resourceManifest.shortNames = new Dictionary<string, string>();
            resourceManifest.belongs = new Dictionary<string, string>();
            var sameNameSet = new HashSet<string>(); // 同名文件检测
            foreach (var abName in resourceManifest.allABFile)
            {
                if (abInfo.abWriteType[abName] != ManifestWriteType.Write)
                {
                    continue;
                }
                var files = abInfo.ab2File[abInfo.abEncryptName2OriginName[abName]];
                foreach (var file in files)
                {
                    var shortName = Path.GetFileNameWithoutExtension(file).ToLower();
                    if (!sameNameSet.Add(shortName))
                    {
                        throw new Exception($"打包异常：出现同名文件\"{shortName}\"！");
                    }
                    resourceManifest.shortNames.Add(shortName, file);
                    resourceManifest.belongs.Add(file, abName);
                }
            }

            foreach (var kv in abInfo.rawNames)
            {
                var shortName = kv.Key;
                if (!sameNameSet.Add(shortName))
                {
                    throw new Exception($"打包异常：出现同名文件\"{shortName}\"！");
                }
            }
            resourceManifest.rawNames = abInfo.rawNames;
            
            EditorUtil.SaveTxtFile(Path.Combine(buildRule.copyPath, BuildConst.ResourceManifestName), ResourceManifest.Encode(resourceManifest));
        }
    }
}
